const router = require('express').Router()
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../common/bee/bee')
const validateToken = require('../../../common/validateToken')

router.get('/getMenuListTotal', async (req, resp) => {
  // 错误处理
  const handleError = (errCode, error) => {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const { sql_type } = req.query
  if (!Bee.StringUtils.isNotBlank(sql_type) || sql_type.length !== 3)
    return handleError(10003, '参数错误')

  // 通过 ---------------------------------------------------------------
  /**
   * 个位值 0:只返回有权限 1:返回所有，包括停用的
   * 十位值 0:默认结构 1:tree结构
   * 百位值 0:返回所有 1:只返回文件夹 2:只返回页面 3:只返回按钮
   */

  let findMenuSql = ''
  if (Bee.StringUtils.getStrLast(sql_type, 1) === '0') {
    // 只返回有权限的
    if (Bee.StringUtils.getStrLast(sql_type, 3) === '0') {
      // 只返回有权限的
      findMenuSql = 'SELECT * FROM menu WHERE menu_status=0'
    } else if (Bee.StringUtils.getStrLast(sql_type, 3) === '1') {
      // 只返回有权限的文件夹
      findMenuSql = 'SELECT * FROM menu WHERE menu_status=0 AND node_type=1'
    } else if (Bee.StringUtils.getStrLast(sql_type, 3) === '2') {
      // 只返回有权限的页面
      findMenuSql = 'SELECT * FROM menu WHERE menu_status=0 AND node_type=2'
    } else if (Bee.StringUtils.getStrLast(sql_type, 3) === '3') {
      // 只返回有权限的按钮
      findMenuSql = 'SELECT * FROM menu WHERE menu_status=0 AND node_type=3'
    }
  } else if (Bee.StringUtils.getStrLast(sql_type, 1) === '1') {
    // 返回所有
    if (Bee.StringUtils.getStrLast(sql_type, 3) === '0') {
      // 返回所有
      findMenuSql = 'SELECT * FROM menu WHERE menu_status=0 OR menu_status=1'
    } else if (Bee.StringUtils.getStrLast(sql_type, 3) === '1') {
      // 只返回文件夹
      findMenuSql = 'SELECT * FROM menu WHERE node_type=1'
    } else if (Bee.StringUtils.getStrLast(sql_type, 3) === '2') {
      // 只返回页面
      findMenuSql = 'SELECT * FROM menu WHERE node_type=2'
    } else if (Bee.StringUtils.getStrLast(sql_type, 3) === '3') {
      // 只返回按钮
      findMenuSql = 'SELECT * FROM menu WHERE node_type=3'
    }
  }

  const [findMenuError, Menu] = await to(
    db.query(
      `${findMenuSql} AND id IN (SELECT
    m.id
    FROM
    menu m, role_menu rm, role r
    WHERE
    r.id=rm.role_id AND rm.menu_id=m.id AND r.id
    IN
    (
    SELECT
    r.id
    FROM
    users u, role r, user_role ur
    WHERE
    u.id=? AND u.id=ur.user_id AND ur.role_id=r.id
    )) ORDER BY sort ASC`,
      [validateTokenSuccess.id]
    )
  )
  // 错误处理
  if (findMenuError || !Menu) return handleError(-1, findMenuError)

  // 转为树形结构
  const toTree = (list, pid) => {
    const arr = []
    list.forEach((item) => {
      if (item.parent_id === pid) {
        arr.push({
          id: item.id,
          name: item.name,
          menu_code: item.menu_code,
          parent_id: item.parent_id,
          node_type: item.node_type,
          icon_url: item.icon_url,
          selected_icon_url: item.selected_icon_url,
          link_url: item.link_url,
          level: item.level,
          path: item.path,
          menu_status: item.menu_status,
          sort: item.sort,
          router_name: item.router_name,
          children:
            toTree(list, item.id).length > 0 ? toTree(list, item.id) : null,
        })
      }
    })
    return arr
  }
  resp.json({
    code: 0,
    msg: status_code[0],
    data:
      Bee.StringUtils.getStrLast(sql_type, 2) === '1'
        ? toTree(Menu, 0)
        : Bee.StringUtils.getStrLast(sql_type, 2) === '0'
        ? Menu
        : [],
  })
})

module.exports = router
